//
//  MainController.swift
//  microblog
//
//  Created by cy on 2017/8/26.
//  Copyright © 2017年 Aisino. All rights reserved.
//

import UIKit

class MainController: UITabBarController {
 
    // MARK: - 私有控件
    /// 撰写按钮
    fileprivate lazy var composeButton: UIButton = UIButton.cz_imageButton(
        "tabbar_compose_icon_add",
        backgroundImageName: "tabbar_compose_button")
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        setupComposeButton()
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    @objc fileprivate func composeStatus() {
        print("composeStatus")
    }
}


// MARK: - 分类，设置子控制器
extension MainController {
    
    /// 设置撰写按钮
    fileprivate func setupComposeButton() {
        tabBar.addSubview(composeButton)
        
        // 计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        // 将向内缩进的宽度
        let w = tabBar.bounds.width / count - 1.0
        
        // CGRectInset 正数向内缩进，负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        print("撰写按钮宽度 \(composeButton.bounds.width)")
        
        // 按钮监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    /// 设置所有的子控制器
    fileprivate func setupChildControllers() {
        
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let prefPath = docDir.appending("/main.json")
        print("本地配置路径： \(prefPath)")
        
        var data = try? Data(contentsOf: URL(fileURLWithPath: prefPath))
        if data == nil {
            let path = Bundle.main.path(forResource: "main", ofType: "json")
            data = try? Data(contentsOf: URL(fileURLWithPath: path!))
        }
        
        guard let dicts = try? JSONSerialization.jsonObject(with: data!, options: []) as? [[String: Any]] ?? [] else {
                return
        }
        
        var ctls = [UIViewController]()
        for dict in dicts {
            ctls.append(childController(dict: dict))
        }
        viewControllers = ctls
    }
    
    // 创建子控制器
    private func childController(dict: [String: Any]) -> UIViewController {
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "."
                + clsName) as? BaseController.Type,
            let visitorDict = dict["visitorInfo"] as? [String: String] else {
                    return BaseController()
        }
        
        let vc = cls.init()
        
        // 设置控制器的访客信息字典
        vc.visitorInfoDictionary = visitorDict
        
        vc.title = title
        vc.tabBarItem.setTitleTextAttributes(
            [NSForegroundColorAttributeName: UIColor.orange],
            for: .selected)
        vc.tabBarItem.setTitleTextAttributes(
            [NSFontAttributeName: UIFont.systemFont(ofSize: 12)],
            for: .normal)
        
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        return NavigationController(rootViewController: vc)
    }
}

